<template>
  <div id="ClassificationManagement">
    <vHeadSpace/>
    <div class="outcontainer">
      <vAsideSpace/>
      <el-main class="main">
        <el-card>
          <el-row>
            <el-col>
              <el-button type="primary" style="margin-bottom: 20px" @click="showAddClassDialog">添加分类</el-button>
            </el-col>
          </el-row>
          <tree-table
              :data="categoriesList" :columns="columns"
              :selection-type="false" :expand-type="false"
              show-index index-text="#" border>
            <template slot="order" slot-scope="scope">
              <el-tag size="mini" v-if="scope.row.typeLevel === 0">一级</el-tag>
              <el-tag size="mini" type="success" v-if="scope.row.typeLevel === 1">二级</el-tag>
              <el-tag size="mini" type="warning" v-if="scope.row.typeLevel === 2">三级</el-tag>
            </template>
            <template slot="operate" slot-scope="scope">
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="editTypeDialog(scope.row)">编辑
              </el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteType(scope.row)">删除</el-button>
            </template>
          </tree-table>
          <!--      分页区-->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pagenum"
              :page-sizes="[2, 5, 10, 20]"
              :page-size="queryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
        </el-card>
      </el-main>
    </div>
    <vFootSpace/>

    <el-dialog
        title="添加知识分类"
        :visible.sync="addClassDialogVisible"
        width="50%"
        @close="addClassDialogClose">
      <el-form :model="addClassForm" :rules="addClassFormRule" ref="addClassFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="addClassForm.typeName"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" label-width="100px">
          <!--          options 来指定数据源 props 指定配置对象 clearable 支持清空-->
          <el-cascader
              clearable
              :options="parentCategoryList"
              :props="cascaderProps"
              v-model="selectedKeys"
              @change="parentCateChange()"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addClassDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassification">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="编辑知识分类"
        :visible.sync="editClassDialogVisible"
        width="50%"
    >
      <el-form :model="editClassForm" :rules="editClassFormRule" ref="editClassFormRef" label-width="100px">
        <el-form-item label="分类名称" prop="typeName">
          <el-input v-model="editClassForm.typeName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editClassDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editClass">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: "ClassificationManagement",
  created() {
    this.getAllTypeList()
  },
  data() {

    // 检验分类名称的规则
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error('分类名称不能为空'));
      } else if (value.length > 40) {
        callback(new Error('分类名称长度不能超过 40 '));
      } else {
        callback();
      }
    };

    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 分类总数
      total: 0,
      // 控制添加分类的dialog
      addClassDialogVisible: false,
      editClassDialogVisible: false,
      editClassForm: {
        typeName: '',
        typeId: 0
      },
      // 分类列表
      categoriesList: [],
      parentCategoryList: [],
      cascaderProps: {
        value: 'typeId',
        label: 'typeName',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true // 父子节点不互相关联，父节点可选择
      },
      // 级联选择器中选中的id值（数组）
      selectedKeys: [],
      columns: [
        {
          label: '分类名称',
          prop: 'typeName'
        },
        {
          label: '分类等级',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate'
        }
      ],
      addClassForm: {
        // 分类名称、分类的父ID、分类的等级
        typeName: '',
        typePId: 0,
        typeLevel: 0
      },
      addClassFormRule: {
        typeName: [
          {validator: validatePass, trigger: 'blur'}
        ]
      },
      editClassFormRule: {
        typeName: [
          {validator: validatePass, trigger: 'blur'}
        ]
      },
      // 需要删除的类型的ID值
      deletedTypeIds: []
    }
  },
  methods: {
    async getAllTypeList() {
      const {data: res} = await this.$axios.post('/konwledgeBase/get_all_type.action', {params: this.queryInfo})
      console.log(res)
      if (!res.status) {
        return this.$message.error('获取分类列表失败')
      }
      this.categoriesList = res.content.result
      this.total = res.content.total
    },
    async getAllParentType() {
      const {data: res} = await this.$axios.post('/konwledgeBase/get_all_type.action', {params: {type: 2}})
      this.parentCategoryList = res.content.result
      console.log(res)
    },
    showAddClassDialog() {
      this.getAllParentType()
      this.addClassDialogVisible = true
    },
    addClassDialogClose() {
      this.$refs.addClassFormRef.resetFields()
      this.selectedKeys = []
      this.addClassForm.typePId = 0
      this.addClassForm.typeLevel = 0
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getAllTypeList()
    },
    handleCurrentChange(newNum) {
      this.queryInfo.pagenum = newNum
      this.getAllTypeList()
    },
    // 级联选择器选择项发生变化时触发函数
    parentCateChange() {
      console.log(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        this.addClassForm.typePId = this.selectedKeys[this.selectedKeys.length - 1]
        this.addClassForm.typeLevel = this.selectedKeys.length
      } else {
        this.addClassForm.typePId = 0
        this.addClassForm.typeLevel = 0
      }
    },
    addClassification() {
      this.$refs.addClassFormRef.validate(async valid => {
        if (valid) {
          const {data: res} = await this.$axios.post('/konwledgeBase/add_type.action', {
            typeName: this.addClassForm.typeName,
            typePId: this.addClassForm.typePId,
            typeLevel: this.addClassForm.typeLevel,
          })
          if (!res.status) {
            return this.$message.error('添加分类失败')
          }
          await this.getAllTypeList();
          this.addClassDialogVisible = false;
          this.$message.success('添加分类成功')
        }
      })
    },
    async deleteType(type) {
      console.log(type)
      this.getDeletedTypeId(type)
      console.log(this.deletedTypeIds)
      const confirmRes = await this.$confirm('确定删除该分类及其子类吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        console.log(err)
      })
      if (confirmRes !== 'confirm') {
        this.deletedTypeIds = []
        return this.$message.info('已取消删除')
      }
      const {data: res} = await this.$axios.post('/konwledgeBase/delete_type_by_id.action', {params: this.deletedTypeIds})
      if (!res.status) {
        return this.$message.error(res.errorCode);
      }
      this.deletedTypeIds = []
      this.queryInfo.type = 3
      this.queryInfo.pagenum = 1
      this.queryInfo.pagesize = 5
      await this.getAllTypeList()
      this.$message.success('删除分类成功')
    },
    // 递归获取所有需要删除的typeId
    getDeletedTypeId(type) {
      this.deletedTypeIds.push(type.typeId)
      if (type.children === null) return;
      type.children.forEach(item => {
        this.getDeletedTypeId(item)
      })
    },
    editTypeDialog(type) {
      this.editClassDialogVisible = true;
      this.editClassForm.typeId = type.typeId
      this.editClassForm.typeName = type.typeName
    },
    editClass() {
      this.$refs.editClassFormRef.validate(async valid => {
        if (valid) {
          const {data: res} = await this.$axios.post('/konwledgeBase/update_type_by_id.action', {params: this.editClassForm})
          if (!res.status) {
            return this.$message.error('修改分类失败')
          }
          this.editClassDialogVisible = false;
          await this.getAllTypeList();
        }
      })
    }
  }
}

</script>

<style>
#ClassificationManagement {
  height: 100%;
  width: 100%;
  background-color: #fff;
}

.outcontainer {
  display: flex;
}

.main {
  padding: 20px;
  margin-top: 60px;
}
</style>